//
//  Hear_SearchViewController.m
//  Hear
//
//  Created by mac on 2018/4/27.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_SearchViewController.h"

#import "Hear_SearchCell.h"

#import "MJRefresh.h"

#import "Hear_SearchListModel.h"

#import "Hear_BaseModel.h"
#import "Hear_AnswerScrollViewController.h" // 回答列表

@interface Hear_SearchViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableview;

/** 搜索 */
@property (nonatomic, strong) UIImageView *searcgImg;
@property (nonatomic, strong) UITextField *searchTF;

/** 颜色数组 */
@property (nonatomic, strong) NSMutableArray *colorArr;

@property (nonatomic, strong) NSMutableDictionary *param;
@property (nonatomic, assign) int page; // 页数

/** 数据源 */
@property (nonatomic, strong) NSMutableArray *listdata;

@end

/** 全局变量 记录是下拉刷新还是上提加载 */
static BOOL isHeader = YES;

@implementation Hear_SearchViewController

- (NSMutableArray *)colorArr {
    if (!_colorArr) {
        _colorArr = [NSMutableArray arrayWithObjects:[UIColor colorWithHexString:@"#FF4C4B"], [UIColor colorWithHexString:@"#4D90FC"], [UIColor colorWithHexString:@"#FEB73D"], [UIColor colorWithHexString:@"#697CFE"], [UIColor colorWithHexString:@"#FF72CE"], [UIColor colorWithHexString:@"#844BEC"], nil];
    }
    return _colorArr;
}

- (NSMutableDictionary *)param {
    if (!_param) {
        _param = [NSMutableDictionary dictionary];
    }
    return _param;
}

- (NSMutableArray *)listdata {
    if (!_listdata) {
        _listdata = [NSMutableArray array];
    }
    return _listdata;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    
    [self creatDefaultParam];
}

- (void)setupUI {
    self.title = @"搜索";
    self.view.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    
    UIView *searchview = [UIView new];
    searchview.backgroundColor = [UIColor whiteColor];
    searchview.layer.masksToBounds = YES;
    searchview.layer.cornerRadius = 5;
    [self.view addSubview:searchview];
    
    [searchview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.view.mas_top).mas_offset(17 * scaleHeight);
        make.leading.mas_equalTo(self.view.mas_leading).mas_offset(18 * scaleWidth);
        make.trailing.mas_equalTo(self.view.mas_trailing).mas_offset(-18 * scaleWidth);
        make.height.mas_equalTo(42 * scaleHeight);
    }];
    
    UIImageView *searcgImg = [[UIImageView alloc] initWithImage:GetImgWithStr(@"搜索-1")];
    self.searcgImg = searcgImg;
    [searchview addSubview:searcgImg];
    
    UITextField *searchTF = [UITextField new];
    searchTF.placeholder = @"输入话题内容........";
    searchTF.font = CustomUIFont(13);
    searchTF.textColor = [UIColor colorWithHexString:@"#A0A0A0"];
    searchTF.delegate = self;
    searchTF.returnKeyType = UIReturnKeySearch;
    self.searchTF = searchTF;
    [searchview addSubview:searchTF];
    
    [searcgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(searchview);
        make.trailing.mas_equalTo(searchTF.mas_leading).mas_offset(-8 * scaleWidth);
        make.leading.mas_equalTo(searchview.mas_leading).mas_offset(108 * scaleWidth);
        make.size.mas_equalTo(CGSizeMake(15.5 * scaleWidth, 16 * scaleHeight));
    }];
    
    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.centerX.mas_equalTo(searchview);
        make.trailing.mas_equalTo(searchview.mas_trailing).mas_offset(-10 * scaleWidth);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
    if (@available(iOS 11.0, *)) {
        self.tableview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    tableView.backgroundColor = [UIColor colorWithHexString:@"#EBEBEB"];
    tableView.showsVerticalScrollIndicator = NO;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.tableFooterView = [UIView new];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.rowHeight = 67 * scaleHeight;
    [tableView registerClass:[Hear_SearchCell class] forCellReuseIdentifier:@"Hear_SearchCell"];
    
    self.tableview = tableView;
    
    [self.view addSubview:tableView];
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.top.mas_equalTo(searchview.mas_bottom).mas_offset(17 * scaleHeight);
    }];
    
}

#pragma mark 获取数据
- (void)creatDefaultParam {
    // 请求数据
    [self.param setObject:[NSString stringWithFormat:@"%d", 10] forKey:@"PageSize"];
    [self.param setObject:USERID forKey:@"CurrentUserLocalId"];
    [self.param setObject:@"0" forKey:@"IsSelf"];
    [self.param setObject:@"" forKey:@"Keywords"];
    [self addRefresh];
    [self.tableview.mj_header beginRefreshing];
}

- (void)addRefresh {
    // 添加头部刷新
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        isHeader = YES;
        self.page = 0;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
        [self requestListData];
    }];
    // 添加尾部加载控件(上提加载)
    self.tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        isHeader = NO;
        self.page += 1;
        [self.param setObject:[NSString stringWithFormat:@"%d", self.page] forKey:@"PageIndex"];
        [self requestListData];
    }];
}

#pragma mark 输入框事件
- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self.param setObject:textField.text forKey:@"Keywords"];
    [self requestListData];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.searchTF) {
        [self.param setObject:textField.text forKey:@"Keywords"];
        [self requestListData];
        return NO;
    }
    return YES;
}

- (void)requestListData {
    
    if (isHeader == YES) {
        [self.listdata removeAllObjects];
    }
    
    YTKApi *api = [YTKApi apiGetWithUrl:@"SoundInfo/Get_GetSoundQuestionsList" para:self.param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
            
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                NSArray *temparr = [NSArray modelArrayWithClass:[Hear_SearchListModel class] json:dict[@"BodyContent"]];
                
                [self.listdata addObjectsFromArray:temparr];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.tableview reloadData];
                });
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            [self.tableview.mj_header endRefreshing];
            [self.tableview.mj_footer endRefreshing];
        }];
    }];
    
}

#pragma mark tableviewdelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listdata.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Hear_SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Hear_SearchCell" forIndexPath:indexPath];
    
    if (self.listdata.count > indexPath.row) {
        Hear_SearchListModel *model = self.listdata[indexPath.row];
        if ([model.QuestionText containsString:@"\n"]) {
            cell.titleLB.text = [model.QuestionText stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        } else {        
            cell.titleLB.text = model.QuestionText;
        }
    }
    
    cell.backcorlor = self.colorArr[indexPath.row % self.colorArr.count];
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    Hear_SearchListModel *model = self.listdata[indexPath.row];
    
    Hear_AnswerScrollViewController *vc = [Hear_AnswerScrollViewController new];
    vc.QuestionID = model.QuestionID;
    [self.navigationController pushViewController:vc animated:YES];

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.searchTF resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
